from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response

from goods.models import SKU
from goods.serializers import CategoriesListSerializer
from users.models import models
# Create your views here.
from users.serializers import AddUserBrowsingHistorySerializer


class UserBrowsingHistoryView(CreateAPIView):
    '''
    用户浏览历史记录
    '''
    serializer_class =  AddUserBrowsingHistorySerializer

    def get(self, request):
        # 1、获取用户对象
        user = request.user
        # 2、查询redis获取sku_id
        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' % user.id, 0, 5)  # [3,1,2]
        # 3、根据sku_id查询商品对象
        skus = SKU.objects.filter(id__in=sku_ids)  #
        # 4、序列化返回商品信息
        ser = CategoriesListSerializer(skus, many=True)

        return Response(ser.data)